package com.mchsdk.paysdk.dialog;

import android.annotation.SuppressLint;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.mchsdk.paysdk.utils.WebViewUtil;
import com.mchsdk.paysdk.callback.PlatformRegisterCallback;
import com.mchsdk.paysdk.config.MCHConstant;
import com.mchsdk.paysdk.utils.MCHInflaterUtils;
import com.mchsdk.paysdk.utils.MCLog;
import com.mchsdk.paysdk.utils.StrUtil;
import com.mchsdk.paysdk.utils.ToastUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

@SuppressLint("NewApi")
public class PlatformQuickRegisterDialog extends DialogFragment {

    /**
     * 日志打印
     */
    private static final String TAG = "PlatformQuickRegisterDialog";

    /**
     * 用户名
     **/
    protected static final String KEY_ACCOUNT = "mc_account";

    /**
     * 密码
     **/
    protected static final String KEY_PASSWORD = "mc_password";

    /**
     * 上下文
     */
    private Context con;
    /**
     * 是否阅读
     */
    boolean isRead=true;
    /**
     * 条款按钮
     */
    Button btnRead;

    /**
     * 返回键监听
     */
    private OnKeyListener mDialogKeyListener;

    /**
     * 注册
     */
    private PlatformRegisterCallback mQuickRegisterCallback;
    /**
     * 手机注册
     */
    private OnClickListener mRegisterClick;

    /**
     * 返回
     */
    private OnClickListener mBackClick;
    /**
     * 失去焦点事件
     */
    private OnFocusChangeListener mFocusChangeListener;
    /**
     * 用户名输入框
     */
    EditText txtAccount;

    /**
     * 密码输入框
     */
    EditText txtPassword;

    /**
     * 重复密码
     */
    EditText txt_mc_platform_quickregister_password_two;
    /**
     * 当前界面对象
     */
    View containerView;
    /**
     * 加载logo的URL
     */
    private String path = MCHConstant.getInstance().getDownloadLogoUrl();
    //下载成功
    private static final int LOAD_SUCCESS = 1;

    //下载失败
    private static final int LOAD_FAIL = -1;

    private ImageView logoImg;

    private HttpURLConnection conn;

    private Bitmap bitmap;
    /**
     * 下载完成后更新UI
     */
    Handler uihandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case LOAD_SUCCESS:

                    if (logoImg != null && bitmap != null) {
                        logoImg.setImageBitmap(bitmap);
                    }
                    MCLog.w(TAG, "下载logo成功");
                    break;

                case LOAD_FAIL:
                    MCLog.w(TAG, "下载logo失败 ");
                    break;
            }
        }
    };

    public PlatformQuickRegisterDialog() {
    }

    @SuppressLint("ValidFragment")
    public PlatformQuickRegisterDialog(Context con) {
        this.con = con;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        containerView = inflater.inflate(MCHInflaterUtils.getIdByName(con,
                "layout", "dialog_mch_platform_quickregister"), container,
                false);
        // 如果有信息,显示加载信息
//		Bundle bundle = getArguments();
//		String account = "";
//		String pwd = "";
//		if (bundle != null) {
//			account = bundle.getString(KEY_ACCOUNT, "");
//			pwd = bundle.getString(KEY_PASSWORD, "");
//			MCLog.e(TAG, "account = " + account + " pwd = " + pwd);
//		}
        //加载logo

        addLogo(containerView);

        txtAccount = (EditText) containerView
                .findViewById(MCHInflaterUtils.getIdByName(con, "id",
                        "txt_mc_platform_quickregister_account"));
        txtPassword = (EditText) containerView.findViewById(MCHInflaterUtils
                .getIdByName(con, "id",
                        "txt_mc_platform_quickregister_password"));
        txt_mc_platform_quickregister_password_two = (EditText) containerView.findViewById(MCHInflaterUtils.getIdByName(con, "id", "txt_mc_platform_quickregister_password_two"));
        btnRead = (Button) containerView.findViewById(MCHInflaterUtils
                .getIdByName(con, "id", "btn_mc_read"));
        btnRead.setBackgroundResource(MCHInflaterUtils.getIdByName(con,
                "drawable", "mch_checkbox_pressed"));
        btnRead.setOnClickListener(readClick);
        containerView.findViewById(
                MCHInflaterUtils.getIdByName(con, "id", "txt_mc_read"))
                .setOnClickListener(readClick);
        containerView.findViewById(
                MCHInflaterUtils.getIdByName(con, "id", "txt_mc_agreement"))
                .setOnClickListener(readClick);
        Button btnBackRegister = (Button) containerView
                .findViewById(MCHInflaterUtils.getIdByName(con, "id",
                        "btn_mc_platform_quickregistertologin"));
//		btnBackRegister.setText(StrUtil.addLine(btnBackRegister.getText().toString().trim()));
        btnBackRegister.setText(btnBackRegister.getText().toString().trim());
        btnBackRegister.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != mBackClick) {
                    dismissAllowingStateLoss();
                    mBackClick.onClick(v);
                }
            }
        });
        // 跳转到手机登录登录
        Button btnNormalRegister = (Button) (Button) containerView
                .findViewById(MCHInflaterUtils.getIdByName(con, "id",
                        "btn_reg_phone"));
        btnNormalRegister.setText(StrUtil.addLine(btnNormalRegister.getText()
                .toString().trim()));
        btnNormalRegister.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != mRegisterClick) {
                    dismissAllowingStateLoss();
                    mRegisterClick.onClick(v);
                }
            }
        });
        Button btnRegister = (Button) (Button) containerView
                .findViewById(MCHInflaterUtils.getIdByName(con, "id",
                        "btn_mc_platform_quickregister"));
        btnRegister.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!isRead) {
                    ToastUtil.show(con, "请阅读并同意用户注册协议");
                    return;
                }
                if (null != mQuickRegisterCallback) {
                    mQuickRegisterCallback.platformRegister(txtAccount
                            .getText().toString(), txtPassword.getText().toString().trim(), txt_mc_platform_quickregister_password_two.getText()
                            .toString(), "", "");
                }
            }
        });

        setCancelable(false);

        this.getDialog().setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(DialogInterface dialog, int keyCode,
                                 KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    dismissAllowingStateLoss();
                    if (null != mDialogKeyListener) {
                        mDialogKeyListener.onKey(dialog, keyCode, event);
                    }
                    return true;
                } else {
                    return false;
                }
            }
        });

        return containerView;
    }

    OnClickListener readClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            isRead = !isRead;
            // 点击的是协议连接
            if (MCHInflaterUtils.getIdByName(con, "id", "txt_mc_agreement") == v
                    .getId()) {
                isRead = true;
                // 显示用户协议
                WebViewUtil.read(con, MCHConstant.getInstance().getUserAgreementUrl());
            }
            if (isRead) {
                btnRead.setBackgroundResource(MCHInflaterUtils.getIdByName(con,
                        "drawable", "mch_checkbox_pressed"));
            } else {
                btnRead.setBackgroundResource(MCHInflaterUtils.getIdByName(con,
                        "drawable", "mch_selectptb_unselected"));
            }
        }
    };

    public void setmDialogKeyListener(OnKeyListener mDialogKeyListener) {
        this.mDialogKeyListener = mDialogKeyListener;
    }

    public void setmQuickRegisterCallback(
            PlatformRegisterCallback mQuickRegisterCallback) {
        this.mQuickRegisterCallback = mQuickRegisterCallback;
    }

    public void setmBackClick(OnClickListener mBackClick) {
        this.mBackClick = mBackClick;
    }

    // 手机号注册
    public void setmRegisterClick(OnClickListener mRegisterClick) {
        this.mRegisterClick = mRegisterClick;
    }

    public void setmOnFocusChangeListener(
            OnFocusChangeListener mFocusChangeListener) {
        this.mFocusChangeListener = mFocusChangeListener;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 设置对话框的样式
        setStyle(STYLE_NO_FRAME,
                MCHInflaterUtils.getIdByName(con, "style", "MCCustomDialog"));
    }

    @Override
    public void onStart() {
        // 1, 设置对话框的大小
        Window window = getDialog().getWindow();
        WindowManager wm = window.getWindowManager();
        Point windowSize = new Point();
        wm.getDefaultDisplay().getSize(windowSize);
        float size_x = 0;
        float size_y = 0;
        int width = windowSize.x;
        int height = windowSize.y;
        if (width >= height) {// 横屏
            size_x = 0.7f;
            size_y = 0.8f;
            window.getAttributes().width = (int) (windowSize.y * size_y * 1.1);
            window.getAttributes().height = (int) (windowSize.y * size_y);
        } else {// 竖屏
            size_x = 0.9f;
            size_y = 0.855f;
            window.getAttributes().width = (int) (windowSize.x * size_x);
            window.getAttributes().height = (int) (windowSize.x * size_y);
        }
        window.setGravity(Gravity.CENTER);
        super.onStart();
    }

    public static class Builder {
        /**
         * 存放数据的容器
         **/
        private Bundle mmBundle;

        private OnKeyListener mmDialogKeyListener;
        private PlatformRegisterCallback mmQuickRegisterCallback;
        private OnClickListener mmBackdClick;
        private OnClickListener mmRegisterClick;
        private OnFocusChangeListener mmOnFocusChangeListener;

        public Builder() {
            mmBundle = new Bundle();
        }

        public Builder setAccount(CharSequence account) {
            mmBundle.putCharSequence(KEY_ACCOUNT, account);
            return this;
        }

        public Builder setPassword(CharSequence pwd) {
            mmBundle.putCharSequence(KEY_PASSWORD, pwd);
            return this;
        }

        public Builder setDialogKeyListener(OnKeyListener mmDialogKeyListener) {
            this.mmDialogKeyListener = mmDialogKeyListener;
            return this;
        }

        public Builder setQuickRegisterCallback(
                PlatformRegisterCallback mmQuickRegisterCallback) {
            this.mmQuickRegisterCallback = mmQuickRegisterCallback;
            return this;
        }

        public Builder setBackdClick(OnClickListener mmBackdClick) {
            this.mmBackdClick = mmBackdClick;
            return this;
        }

        // 手机号注册
        public Builder setRegisterClick(OnClickListener mmRegisterClick) {
            this.mmRegisterClick = mmRegisterClick;
            return this;
        }

        public Builder setOnFocusChangeListener(
                OnFocusChangeListener mmOnFocusChangeListener) {
            this.mmOnFocusChangeListener = mmOnFocusChangeListener;
            return this;
        }

        private PlatformQuickRegisterDialog create(Context con) {
            final PlatformQuickRegisterDialog dialog = new PlatformQuickRegisterDialog(
                    con);
            // 1,设置显示内容
            dialog.setArguments(mmBundle);

            dialog.setmDialogKeyListener(mmDialogKeyListener);
            dialog.setmQuickRegisterCallback(mmQuickRegisterCallback);
            dialog.setmBackClick(mmBackdClick);
            dialog.setmRegisterClick(mmRegisterClick);
            dialog.setmOnFocusChangeListener(mmOnFocusChangeListener);
            return dialog;
        }

        public PlatformQuickRegisterDialog show(Context con, FragmentManager fm) {
            if (fm == null) {
                MCLog.e(TAG, "show error : fragment manager is null.");
                return null;
            }
            PlatformQuickRegisterDialog dialog = create(con);
            MCLog.d(TAG, "show SelectPTBTypeDialog.");
            dialog.show(fm, TAG);
            return dialog;
        }
    }

    /**
     * 加载图 logo
     */
    private void addLogo(View view) {

        logoImg = (ImageView) view.findViewById(MCHInflaterUtils
                .getIdByName(con, "id", "mch_iv_log"));
        new Thread(new Runnable() {
            @Override
            public void run() {


                getBitmap();
            }


        }).start();
    }

    private void getBitmap() {
        URL url = null;

        InputStream is = null;

        try {
            url = new URL(path);

            conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("GET");

            conn.connect();

            if (conn.getResponseCode() == 200) {
                is = conn.getInputStream();
                bitmap = BitmapFactory.decodeStream(is);

                uihandler.sendEmptyMessage(LOAD_SUCCESS);
            }

        } catch (MalformedURLException e) {
            uihandler.sendEmptyMessage(LOAD_FAIL);
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {


            try {
                if (is != null) {
                    is.close();
                }


            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

//	@Override
//	public void show(FragmentManager manager, String tag) {
//		FragmentTransaction ft = manager.beginTransaction();
//		ft.add(this, tag);
//        ft.commitAllowingStateLoss();
//	}

}
